/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wolfking.sharding.slave;

import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;
import org.apache.shardingsphere.spring.boot.prop.SpringBootPropertiesConfiguration;
import org.apache.shardingsphere.spring.boot.rule.LocalRulesCondition;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;

/**
 * Spring boot starter configuration.
 */
@Configuration
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ComponentScan("org.apache.shardingsphere.spring.boot.converter")
@ConditionalOnProperty(prefix = "spring.shardingsphere.slave", name = "enabled", havingValue = "true")
public class SpringBootConfigurationSlave implements EnvironmentAware {


    private String databaseName;

    private final Map<String, DataSource> dataSourceMap = new LinkedHashMap<>();

    @Bean
    @Autowired(required = false)
    @Conditional(LocalRulesCondition.class)
    public DataSource shardingSphereDataSourceSlave(final ObjectProvider<List<RuleConfiguration>> rules, final ObjectProvider<ModeConfiguration> modeConfig,
                                               SpringBootPropertiesConfiguration props) throws SQLException {
        Collection<RuleConfiguration> ruleConfigs = Optional.ofNullable(rules.getIfAvailable()).orElseGet(Collections::emptyList);
        return ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig.getIfAvailable(), dataSourceMap, ruleConfigs, props.getProps());
    }

//    /**
//     * Get data source bean from registry center.
//     *
//     * @param modeConfig mode configuration
//     * @return data source bean
//     * @throws SQLException SQL exception
//     */
//    @Bean
//    @ConditionalOnMissingBean(DataSource.class)
//    @Qualifier("shardingSphereDataSourceSlave")
//    public DataSource dataSource(final ModeConfiguration modeConfig, SpringBootPropertiesConfiguration props) throws SQLException {
//        return !dataSourceMap.isEmpty() ? ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig, dataSourceMap, Collections.emptyList(), props.getProps())
//                : ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig);
//    }


    @Override
    public final void setEnvironment(Environment environment) {
        dataSourceMap.putAll(SlaveDataSourceMapSetter.getDataSourceMap(environment));
        databaseName = SlaveDatabaseNameSetter.getDatabaseName(environment);
    }
}
